package com.gxy.learn.thread.example.abcdef;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.LockSupport;

/**
 * @description:
 * @author: gaoxueyong
 * @Date: 2022/11/3 12:46
 */
@Slf4j
public class A1B2 {
    static Thread a;
    static Thread b;

    public static void main(String[] args) {
//        objectWaitNotifyA1B2C3();
        lockSupportA1B2C3();
    }


    public static void objectWaitNotifyA1B2C3() {
        final Object o = new Object();
        char[] a1 = "12345".toCharArray();
        char[] a2 = "abcde".toCharArray();
        new Thread(() -> {
            synchronized (o) {
                for (char c : a1) {
                    log.info("{}", c);
                    try {
                        o.notify();
                        o.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                o.notify();
            }

        }, "a1").start();
        new Thread(() -> {
            synchronized (o) {
                for (char c : a2) {
                    log.info("{}", c);
                    try {
                        o.notify();
                        o.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                o.notify();
            }

        }, "a2").start();
    }

    public static void lockSupportA1B2C3() {
        char[] a1 = "12345".toCharArray();
        char[] a2 = "abcde".toCharArray();
        a = new Thread(() -> {
            for (char c : a1) {
                log.info("{}", c);
                LockSupport.unpark(b);
                LockSupport.park();
            }

        }, "a1");
        b = new Thread(() -> {
            for (char c : a2) {
                log.info("{}", c);
                LockSupport.park();
                LockSupport.unpark(a);
            }
        }, "a2");
        a.start();
        b.start();
    }
}
